package com.itsenpupulai.bdtest.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.itsenpupulai.bdtest.R;
import com.itsenpupulai.bdtest.bean.User;
import com.itsenpupulai.bdtest.utils.DBUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int BD_REQUEST_CODE = 100;
    private TextView tv_location;
    private LocationClient mLocationClient;
    private StringBuilder sb = new StringBuilder();
    private Button btn_location;
    private ScrollView sv;
    private String[] pessStr = new String[]{

            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};


    private User user = new User();
    private List<User> list = new ArrayList<>();
    private long startTime ;
    private Button cleanData;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        tv_location = (TextView) findViewById(R.id.tv_location);
        btn_location = (Button) findViewById(R.id.btn_location);
        sv = (ScrollView) findViewById(R.id.sv_location);
        cleanData = (Button) findViewById(R.id.btn_delete);

        startTime = new Date().getTime();


        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyListener());

        InitLocation();

        btn_location.setOnClickListener(this);
        cleanData.setOnClickListener(this);









    }










    @Override
    protected void onResume() {
        super.onResume();
        if (!checkLocationPermission(this)) {
            showOpenLocationDialog(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_location:
                if (!mLocationClient.isStarted()) {
                    mLocationClient.start();
                }
                sb.delete(0, sb.length());
                list = DBUtil.queryAll();

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sb.append(dateFormat.format(startTime));
                Log.d("1111111111111", "sb--->" + sb.length());

                for (int i1 = 0; i1 < list.size(); i1++) {
                    sb.append("\n\n");
                    sb.append(i1 +"\n"+ list.get(i1).toString());

                }
                tv_location.setText(sb.toString());
                 sv.fullScroll(ScrollView.FOCUS_DOWN);
                break;
            case R.id.btn_delete:
                DBUtil.deleteAll();
                break;
        }

    }

    // Android6.0系统申请读写外部存储的运行时权限（该方法在需要操作外部存储时调用，或在相关初始化操作中调用）
    private void requestPermissions() {
        // 如果未获得外部存储读写权限，则申请
        if (
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ) {
            // 申请权限
            ActivityCompat.requestPermissions(this,pessStr , BD_REQUEST_CODE);
        }
    }



    // 请求运行时权限的回调方法
    // requestCode：用于识别申请权限的请求码
    // permissions：请求的权限
    // grantResults：对应权限的请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case BD_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 允许权限
                    Toast.makeText(MainActivity.this, "允许权限", Toast.LENGTH_SHORT).show();
                    InitLocation();
                } else {
                    // 拒绝权限
                    Toast.makeText(MainActivity.this, "拒绝权限", Toast.LENGTH_SHORT).show();
                    this.finish();
                }
//                Toast.makeText(this, "未成功", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void InitLocation() {
        // // 地图初始化
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度，默认值gcj02 bd09ll
        option.setScanSpan(60000);// 设置发起定位请求的间隔时间为5000ms,改为10秒
        option.setIsNeedAddress(true);// 需要城市、街道等信息
        option.setOpenGps(true);

        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    //判断GPS 网络是否开启
    public static boolean checkLocationPermission(Context context) {
        try {
            boolean isGps = false; // 判断GPS定位是否启动
            boolean isNetwork = false; // 判断网络定位是否启动
            if (context != null) {
                LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                if (locationManager != null) {
                    // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
                    isGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                    // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
                    isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                }
                if (isGps || isNetwork) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        }
        return false;
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case BD_REQUEST_CODE:
//                boolean b = true;
//                for (int i1 = 0; i1 < grantResults.length; i1++) {
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                        b = false;
//                    }
//                }
//
//                if (b){
//                    InitLocation();
//                }
//
//                    InitLocation();
//                    break;
//            default:
//                        break;
//        }
//    }





    public static Dialog showOpenLocationDialog(final Context context) {

        final Dialog dialog = new AlertDialog.Builder(context).create();
        try {
            dialog.setCancelable(true);
            dialog.show();
            dialog.getWindow().setContentView(
                    R.layout.dialog_shijian_toast_layout);
            TextView contentTextView3 = (TextView) dialog.getWindow()
                    .findViewById(R.id.dialog_shijian_tv_content);
            contentTextView3.setText("地点服务被禁用，请启用定位服务！");
            dialog.getWindow().findViewById(R.id.dialog_shijian_tv_ensure)
                    .setOnClickListener(new View.OnClickListener() {// 点击是
                        @Override
                        public void onClick(View arg0) {
                            dialog.dismiss();
                            context.startActivity(new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dialog;
    }

    class MyListener implements BDLocationListener{
        @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                setUser(bdLocation);
//
//                sb.append("\n\n" + (++i) + " " );
//            long time = new Date().getTime();
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            sb.append(dateFormat.format(time));
//
//                if (bdLocation.getLocType() == 161 && bdLocation.getLatitude() != 0) {// 网络定位成功
////                    Log.e("MyApplication中定位", "网络定位成功");
//                    sb.append("网络定位成功" +"\n" );
//                    sb.append("--Time:" + bdLocation.getTime() + "Long:" + Float.parseFloat(String.valueOf(bdLocation.getLongitude())) + "Lat:" + Float.parseFloat(String.valueOf(bdLocation.getLatitude())) + bdLocation.getAddrStr() );
//
//
//                } else if (bdLocation.getLocType() == 61 && bdLocation.getLatitude() != 0) {// gps定位
////                    Log.e("MyApplication中定位", "GPS定位成功");
//                    sb.append("GPS定位成功" + "\n");
//                    sb.append("--Time:" + bdLocation.getTime() + "Long:" + Float.parseFloat(String.valueOf(bdLocation.getLongitude())) + "Lat:" + Float.parseFloat(String.valueOf(bdLocation.getLatitude())) + bdLocation.getAddrStr() );
//                }else if (bdLocation.getLocType() == 167){
////                    long time = new Date().getTime();
////                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////                    sb.append(dateFormat.format(time));
//                    sb.append("定位失败：" + 167 + "\n" );
//                    Toast.makeText(MainActivity.this, "请开启定位权限", Toast.LENGTH_SHORT).show();
//                }else {
////                    Log.e("MyApplication中定位", "定位失败");
////                    long time = new Date().getTime();
////                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////                    sb.append(dateFormat.format(time));
//                    sb.append("定位失败--未知错误" );
//                }

//                if (bdLocation.getLocType() == BDLocation.TypeGpsLocation){
//
//                    // GPS定位结果
//                    sb.append("\nspeed : ");
//                    sb.append(bdLocation.getSpeed());    // 单位：公里每小时
//
//                    sb.append("\nsatellite : ");
//                    sb.append(bdLocation.getSatelliteNumber());    //获取卫星数
//
//                    sb.append("\nheight : ");
//                    sb.append(bdLocation.getAltitude());    //获取海拔高度信息，单位米
//
//                    sb.append("\ndirection : ");
//                    sb.append(bdLocation.getDirection());    //获取方向信息，单位度
//
//                    sb.append("\naddr : ");
//                    sb.append(bdLocation.getAddrStr());    //获取地址信息
//
//                    sb.append("\ndescribe : ");
//                    sb.append("gps定位成功");
//
//                } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
//
//                    // 网络定位结果
//                    sb.append("\naddr : ");
//                    sb.append(bdLocation.getAddrStr());    //获取地址信息
//
//                    sb.append("\noperationers : ");
//                    sb.append(bdLocation.getOperators());    //获取运营商信息
//
//                    sb.append("\ndescribe : ");
//                    sb.append("网络定位成功");
//
//                } else if (bdLocation.getLocType() == BDLocation.TypeOffLineLocation) {
//
//                    // 离线定位结果
//                    sb.append("\ndescribe : ");
//                    sb.append("离线定位成功，离线定位结果也是有效的");
//
//                } else if (bdLocation.getLocType() == BDLocation.TypeServerError) {
//
//                    sb.append("\ndescribe : ");
//                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
//
//                } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkException) {
//
//                    sb.append("\ndescribe : ");
//                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
//
//                } else if (bdLocation.getLocType() == BDLocation.TypeCriteriaException) {
//
//                    sb.append("\ndescribe : ");
//                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
//
//                }else {
////                    Log.e("MyApplication中定位", "定位失败");
//                    sb.append("定位失败--未知错误" + "\n");
//                }
            }

        public void setUser(BDLocation location){
            if (location != null) {
                long time = new Date().getTime();
                user.setId(time);
                user.setAddress(location.getAddress() + "");
                user.setAddressStr(location.getAddrStr());
                user.setLongitude(String.valueOf((float) location.getLongitude()));
                user.setLatitude(String.valueOf((float) location.getLatitude()));
                user.setDate(location.getTime());
                if (location.getLocType() == 161) {
                    user.setType("网络定位成功");
                }else if (location.getLocType() == 61){
                    user.setType("GPS定位成功");
                }
                DBUtil.insertUser(user);
            }
        }

            @Override
            public void onConnectHotSpotMessage(String s, int i) {

            }

    }
}
